package com.lujianfei.filesend

import android.os.Process
import androidx.databinding.Observable
import androidx.databinding.Observable.OnPropertyChangedCallback
import androidx.fragment.app.Fragment
import com.lujianfei.common.AppUtils
import com.lujianfei.filesend.base.BaseActivity
import com.lujianfei.filesend.databinding.ActivityMainBinding
import com.lujianfei.filesend.ui.dialog.DialogButton
import com.lujianfei.filesend.ui.dialog.DialogUtils
import com.lujianfei.filesend.ui.tab.TabConnectFragment
import com.lujianfei.filesend.ui.tab.TabTransferFragment
import com.lujianfei.filetransfer.FileTransferManager
import com.lujianfei.filetransfer.TcpManager
import kotlin.system.exitProcess


/**
 * Author: lujianfei
 * Date: 2023/10/16 13:42
 * Description: 主页
 */

class MainActivity: BaseActivity<ActivityMainBinding>() {

    private var currentFragment: Fragment?= null
    private val mTabConnectFragment by lazy { TabConnectFragment() }
    private val mTabTransferFragment by lazy { TabTransferFragment() }
    private val viewModel: MainViewModel by lazy { buildViewModel() }
    override fun resourceId() = R.layout.activity_main

    override fun initView() {
        binding?.vm = viewModel
        switchFragment(mTabConnectFragment)
    }

    override fun initData() {
        startServer()
    }

    override fun initEvent() {
        viewModel.tabSelected.addOnPropertyChangedCallback(object : OnPropertyChangedCallback() {
            override fun onPropertyChanged(sender: Observable?, propertyId: Int) {
                when (viewModel.tabSelected.get()) {
                    0-> {
                        switchFragment(mTabConnectFragment)
                    }
                    1-> {
                        switchFragment(mTabTransferFragment)
                    }
                }
            }
        })
    }

    private fun switchFragment(fm: Fragment) {
        val tag = fm::class.java.simpleName
        val fmFinal = supportFragmentManager.findFragmentByTag(tag)?:fm
        if (currentFragment == fmFinal) return
        val transaction = supportFragmentManager.beginTransaction()
        currentFragment?.let { transaction.hide(it) }
        if (fmFinal.isAdded) {
            transaction.show(fmFinal)
        } else {
            transaction.add(R.id.fragment_container, fmFinal, tag)
        }
        transaction.commitAllowingStateLoss()
        currentFragment = fmFinal
    }

    private fun startServer() {
        TcpManager.instance.startServer()
        FileTransferManager.instance.startFileServer(port = TcpManager.port)
    }

    override fun onBackPressed() {
        DialogUtils.show(this, content = "确认退出当前连接?", confirm = DialogButton("确认", onClickListener = {
            TcpManager.instance.release()
            FileTransferManager.instance.release()
            super.onBackPressed()
            AppUtils.killSelf()
        }), cancel = DialogButton("取消", onClickListener = {

        }))
    }
}
